package com.hyx.bookManager.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

/**
 * @ClassName EmailUtil
 * @Description TODO
 * @Author 黄乙轩
 * @Date 2021/5/4 13:12
 * @Version 1.0
 **/

@Component
public class EmailUtil {

    @Resource
    private TemplateEngine templateEngine;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static final String subject="注册验证";
    private static final String MONITOR_TITLE="警告!";

    public String sendCodeEmail(String to, String text) throws IOException, MessagingException {
        Context context = new Context();
        context.setVariable("code",text);
        String process = templateEngine.process("emailTemplate",context);
        MimeMessage message =  mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setText(process,true);
        helper.setSubject(subject);
        mailSender.send(message);
        return process;
    }

    public String sendMonitorEmail(String to,String imgName) throws MessagingException {
        Context context = new Context();
        context.setVariable("imgname",imgName);
        String process = templateEngine.process("monitorTemplate",context);
        MimeMessage message =  mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setText(process,true);
        helper.setSubject(MONITOR_TITLE);
        mailSender.send(message);
        return process;
    }
}
